import 'package:dio/dio.dart' as dio_form_data;
import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';
import 'package:wan_android_flutter/common/network/model/search_result_model.dart';

import '../../common/network/http_util.dart';
import '../../common/network/json_parse.dart';
import 'search_result_state.dart';

class SearchResultLogic extends BaseController {
  final SearchResultState state = SearchResultState();

  EasyRefreshController controller = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments is String) {
      state.keyword.value = Get.arguments;
    }
  }

  @override
  void onLoadData() {
    super.onLoadData();
    search();
  }

  Future<void> search() async {
    dio_form_data.FormData formData = dio_form_data.FormData.fromMap({'k': state.keyword});
    final response = await httpUtil.post("/article/query/${state.pageIndex}/json", data: formData);
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final searchResultModel = JsonParse.fromJsonMap<SearchResultModel>(response.data);
      if (searchResultModel?.data?.datas?.isNotEmpty == true) {
        if (state.pageIndex == 0) {
          state.searchResultList.assignAll(searchResultModel!.data!.datas!);
        } else {
          state.searchResultList.addAll(searchResultModel!.data!.datas!);
        }
        state.searchResults.assignAll(state.searchResultList);
        controller.finishRefresh();
        controller.finishLoad();
      }
    }
  }
}
